package cs.upt.awp.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import cs.upt.awp.data.*;

public class TravelNotesDAO implements DataDAO<TravelNote>{

	@Autowired
	SessionFactory sessionFactory;

	Session session = null;
	Transaction tx = null;    
	
	@Override
	public boolean addEntity(TravelNote entity) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		session.save(entity);
		tx.commit();
		session.close();
		return false;
	}

	@Override
	public TravelNote getEntityById(long id) throws Exception {
		session = sessionFactory.openSession();
		TravelNote note = (TravelNote) session.load(TravelNote.class, new Long(id));
		tx = session.getTransaction();
		session.beginTransaction();
		tx.commit();
		//session.close();
		return note;
	}
		

	@SuppressWarnings("unchecked")
	@Override
	public List<TravelNote> getEntityList() throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		List<TravelNote> notes = session.createCriteria(
				TravelNote.class).list();
		tx.commit();
		session.close();
		return notes;
	}

	@Override
	public boolean deleteEntity(long id) throws Exception {
		session = sessionFactory.openSession();
		Object o = session.load(TravelNote.class, id);
		tx = session.getTransaction();
		session.beginTransaction();
		session.delete(o);
		tx.commit();
		session.close();
		return false;
	}

	@SuppressWarnings("unchecked")
	public List<TravelNote> getRecordNotes(long recordId) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		System.out.println("record id: " + recordId);
		Query q = session.createQuery("select tn from travelnotes tn where tn.record.id = :recordId"); 
		q.setLong("recordId", recordId);
		List<TravelNote> notes =q.list();
		tx.commit();
		session.close();
		return notes;
	}
	
	public boolean updateNote(TravelNote note) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		TravelNote travelNote = (TravelNote) session.load(TravelNote.class, new Long(note.getId()));		
		travelNote.setTitle(note.getTitle());
		travelNote.setNote(note.getNote());
		session.save(travelNote);
		tx.commit();
		session.close();
		return false;
	}

}
